package com.example.tianyutong.qanda.ui.menu;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Toast;

import com.example.tianyutong.qanda.R;
import com.example.tianyutong.qanda.base.BaseActivity;
import com.example.tianyutong.qanda.databinding.ActivityLoginBinding;
import com.example.tianyutong.qanda.http.rx.RxBus;
import com.example.tianyutong.qanda.http.rx.RxCodeConstants;
import com.example.tianyutong.qanda.viewmodel.menu.LoginViewModel;

/**
 * 玩安卓登录
 *
 * @author tianyutong
 */
public class LoginActivity extends BaseActivity<LoginViewModel, ActivityLoginBinding> {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setTitle("玩安卓登录");
        showContentView();
        bindingView.setViewModel(viewModel);
    }

    public void register(View view) {
        viewModel.register().observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(@Nullable Boolean aBoolean) {
                if (aBoolean != null && aBoolean) {
                    Toast.makeText(LoginActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void login(View view) {
        viewModel.login().observe(this, this::loadSuccess);
    }

    /**
     * 注册或登录成功
     */
    public void loadSuccess(Boolean aBoolean) {
        if (aBoolean != null && aBoolean) {
            RxBus.getDefault().post(RxCodeConstants.LOGIN, true);
            Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    public static void start(Context mContext) {
        Intent intent = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(intent);
    }
}
